﻿namespace Pathfinding.Serialization
{
    using Pathfinding;
    using System;
    using System.IO;

    public class GraphSerializationContext
    {
        public readonly int graphIndex;
        private readonly GraphNode[] id2NodeMapping;
        public readonly BinaryReader reader;
        public readonly BinaryWriter writer;

        public GraphSerializationContext(BinaryWriter writer)
        {
            this.writer = writer;
        }

        public GraphSerializationContext(BinaryReader reader, GraphNode[] id2NodeMapping, int graphIndex)
        {
            this.reader = reader;
            this.id2NodeMapping = id2NodeMapping;
            this.graphIndex = graphIndex;
        }

        public GraphNode GetNodeFromIdentifier(int id)
        {
            if (this.id2NodeMapping == null)
            {
                throw new Exception("Calling GetNodeFromIdentifier when serializing");
            }
            if (id == -1)
            {
                return null;
            }
            GraphNode node = this.id2NodeMapping[id];
            if (node == null)
            {
                throw new Exception("Invalid id");
            }
            return node;
        }

        public int GetNodeIdentifier(GraphNode node)
        {
            return ((node != null) ? node.NodeIndex : -1);
        }
    }
}

